package com.hcloud.auth.audit;

import com.hcloud.audit.api.event.LoginLogEvent;
import com.hcloud.audit.core.bean.LoginLog;
import com.hcloud.audit.core.util.IPUtils;
import com.hcloud.auth.api.config.LoginType;
import com.hcloud.auth.third.ThirdLoginUtil;
import com.hcloud.common.core.util.SpringUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Auther hepangui
 * @Date 2018/11/20
 */
@Service
public class LoginLogService {
    private void saveLoginLog(String account, String username, boolean success, String msg) {

        try {
            var request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            var uri = request.getRequestURI();
            var userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
            var bean = LoginLog.builder().username(username)
                    .account(account).ipAddr(IPUtils.getIpAddr(request))
                    .browser(userAgent.getBrowser().getName())
                    .msg(msg)
                    .device(userAgent.getOperatingSystem().getName())
                    .osName(userAgent.getOperatingSystem().getDeviceType().getName())
                    .success(success ? 1 : 0).build();
            LoginType loginType = ThirdLoginUtil.getLoginType(request);
            switch (loginType) {
                case weixin:
                    bean.setLoginType("微信");
                    break;
                case qq:
                    bean.setLoginType("qq");
                    break;
                case pass:
                    bean.setLoginType("账号");
                    break;
                case gitee:
                    bean.setLoginType("码云");
                    break;
                case mobile:
                    bean.setLoginType("手机");
                    break;
            }
            SpringUtil.publishEvent(new LoginLogEvent(bean));
        } catch (Exception e) {
        }
    }

    public void saveSuccessLog(String account, String username) {
        this.saveLoginLog(account, username, true, "");
    }

    public void saveErrorLog(String account, String msg) {
        if (account == null) {
            var request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            var username = request.getParameter("username");
            if(username!=null && username.length()>0){
                account = username;
            }else{
                var mobile = request.getParameter("mobile");
                if (mobile != null) {
                    account = mobile;
                } else {
                    account = "/";
                }
            }

        }
        this.saveLoginLog(account, "", false, msg);
    }
}
